<?php

namespace app\admin\controller\zhongzhuan\baiying;

use app\common\controller\Backend;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Byaitaskphone extends Backend
{

    /**
     * Byaitaskphone模型对象
     * @var \app\admin\model\zhongzhuan\baiying\Byaitaskphone
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\zhongzhuan\baiying\Byaitaskphone;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->assignconfig("yixiang_list", $this->model->getYixiangList());
        
        
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    
    
    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index1()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $table = 'fa_' . getBaiYingDataTable();
        $sql  = "SELECT * FROM `{$table}`  WHERE  `status` = 0  AND `yixiang_value` IN ('A','B')";
      
        $list = Db::field('*')
                ->table( '('. $sql .') a')
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items(),'sql'=>db(getBaiYingDataTable())->getLastSql()];
        return json($result);
    }
    
    
    public function assignkehu($ids){
        
        
        $row = [];
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                
                $result = false;
                Db::startTrans();
                try {
                    $today_start_time = strtotime("today");
                    $assign_id = db('ec_assign_kehu')->where(['createtime'=>['>',$today_start_time]])->order('id desc')->value('id');
                   if(empty($assign_id)){
                        $this->error('分配失败');
                        exit;
                    }
                    
                   $msg = '分配成功，待推送';
                    $controller = '\app\common\controller\zhongzhuan\Autoassign';
                    $param = [];
//                    $user_info = db('ec_user')->field('id ecid,userid')->where('id',$params['user_id'])->find();
//                    $user_info['assign_id'] = 0;
                    
                    
                    $user_id_arr = explode(',', $params['user_id']);
                    $assign_user_detail = [];
                    foreach ($user_id_arr as $value){
                        $assign_user_detail[$value]['shoudong_fenpei_people'] = 0;
                    }
                    
                    
                    
                    $kehuidlist = explode(',', $ids);
                    $assignData = [];
                    $kehuUpdateId = [];
                    $success_int = $fail_int = 0;
                    
                    foreach ($kehuidlist as $value){
                        
                        $kehu_item = db(getBaiYingDataTable())->where('id',$value)->find();
                        $kehu_item['byid'] = $kehu_item['id'];                        
                        if(!empty($kehu_item['status']))             {
                            $fail_int = $fail_int + 1;
                            continue;
                        }               
                        
                        $result = $this->getAssingUserId($assign_user_detail);
                        $user_id = $result['user_id'];
                        $assign_user_detail = $result['list'];
                        
                        
                        $user_info = db('ec_user')->field('id ecid,userid')->where('id',$user_id)->find();
                        $user_info['assign_id'] = $assign_id;
                        $data = call_user_func_array(array($controller, 'assingSignleKehuToUser'),array($kehu_item,$user_info));
                        
                                               
                        $assign_user_detail[$user_id]['shoudong_fenpei_people']=  $assign_user_detail[$user_id]['shoudong_fenpei_people'] + 1;
                        
                        $success_int = $success_int + 1;
                        $kehuUpdateId[] = $kehu_item['id'];
                        $assignData[] = $data;
                    }
                    
                    if(!empty($assignData)){
                        
                        foreach ($assign_user_detail as $k =>$v){
                            $info = db('ec_assign_kehu_detail')->where(['assign_id'=>$assign_id,'user_id'=>$k])->find();
                            if(empty($info)){                              
                                db('ec_assign_kehu_detail')->insertGetId([
                                    'assign_id'=>$assign_id,
                                    'user_id'=>$k,
                                    'shoudong_fenpei_people'=>$v['shoudong_fenpei_people'],
                                    'createtime'=>time()
                                ]);
                            }else{
                                $shoudong_fenpei_people = $v['shoudong_fenpei_people'] + $info['shoudong_fenpei_people'];
                                db('ec_assign_kehu_detail')->where(['assign_id'=>$assign_id,'user_id'=>$k])->update(['shoudong_fenpei_people'=>$shoudong_fenpei_people]);
                            }
                            
                            
                        }
                        
                        
                        
                        db('ec_aiuser_to_ecuser')->insertAll($assignData);
                        db(getBaiYingDataTable())->where('id','in',$kehuUpdateId)->update([
                            'status'=>1,'type'=>1
                        ]);
                    }
                    $total = count($kehuidlist);
                    $msg = "计划分配{$total}人;成功{$success_int}人;失败{$fail_int}人(已分配)。";
                    
                    $result = true;
                    
                                     
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success($msg);
                } else {
                    $this->error('分配失败');
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
      
        $this->view->assign('row',$row);
        return $this->view->fetch();
        
    }
    
    
    public  function getAssingUserId($list){
        $end_list = [];
        $min = 999999;
        $user_id = 0;
        foreach ($list as $key=> $value){
//            if($value['success_people'] >= $value['people']) continue;
            if($value['shoudong_fenpei_people'] < $min){
                $min = $value['shoudong_fenpei_people'];
                $user_id = $key;
            }
        }
                       
        
        
        return ['user_id'=>$user_id,'list'=>$list] ;
    }


}
